package com.java.comprehensive.other.sort;


class Solution {
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(2);
        ListNode listNode2 = new ListNode(4);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(5);
        ListNode listNode5 = new ListNode(6);
        ListNode listNode6 = new ListNode(4);
        listNode2.next = listNode3;
        listNode1.next = listNode2;
        listNode5.next = listNode6;
        listNode4.next = listNode5;
        System.out.println("l1:" + listNode1);
        System.out.println("l2:" + listNode4);
        Solution solution = new Solution();
        ListNode listNode = solution.addTowNumbers_1(listNode1, listNode4);
        System.out.println(listNode);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(-1);
        ListNode cur = result;
        System.out.println(result.getClass());
        System.out.println(cur.getClass());
        int c = 0; // 进位
        while (l1 != null || l2 != null) {
            int a = l1 == null ? 0 : l1.val;
            int b = l2 == null ? 0 : l2.val;
            cur.next = new ListNode((a + b + c) % 10);  // 当前节点指向下一个节点

            cur = cur.next;  // 当前节点指向最后一个节点
            c = (a + b + c) / 10;                   // 更新进位
            l1 = l1 == null ? null : l1.next;   // 更新要计算的下一个数
            l2 = l2 == null ? null : l2.next;
        }

        if (c != 0) {
            cur.next = new ListNode(c);
        }

        // 非空链表，所以至少一个
        return result.next;
    }

    public ListNode addTowNumbers_1(ListNode l1, ListNode l2) {
        ListNode result = new ListNode();
        ListNode temp  = result;
        while (l1 != null || l2 != null) {
            int a = l1 == null ? 0 : l1.val;
            int b = l2 == null ? 0 : l2.val;
            temp.next =new ListNode(a + b);
            temp = temp.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        return result.next;
    }
}